#!/usr/bin/env python

from optparse import OptionParser

from sqlobject import *

import magicdate
from retrieve import retrieve


if __name__ == '__main__':
    # Variables and buoys.
    vars = ['t', 's', 'd', 'rad', 'rain', 'iso', 'met']
    buoys = ['0n10w', '14s32w', '2n10w', '10s10w', '8s30w', '19s34w', '2s10w', '6s10w', '8n38w', '15n38w', '4n38w', '0n35w', '0n0e', '12n38w', '0n23w']

    parser = OptionParser(option_class=magicdate.MagicDateOption)
    parser.add_option('-f', '--frequency', dest='frequency', default='dy', choices=['dy', 'hr', '10m', 'hres'])
    parser.add_option('-b', '--buoy', dest='buoy', default=None, choices=buoys)
    parser.add_option('-v', '--variable', dest='variable', default=None, choices=vars)
    parser.add_option('-s', '--start', dest='start', type='magicdate', default=None)
    parser.add_option('-e', '--end', dest='end', type='magicdate', default='today')
    parser.add_option('-d', '--dsn', dest='dsn', default=None)
    options, args = parser.parse_args()

    # Variables and buoys to retrieve.
    if options.variable is not None: vars = [options.variable]
    if options.buoy is not None: buoys = [options.buoy]

    # Set up a connection.
    connection = connectionForURI(options.dsn)
    sqlhub.processConnection = connection

    # Stupid Python 2.3
    if isinstance(options.end, str): options.end = magicdate.magicdate(options.end)
    if isinstance(options.start, str): options.start = magicdate.magicdate(options.start)

    # Get data.
    for var in vars:
        for buoy in buoys:
            retrieve(buoy, var, options.start, options.end, options.frequency)
